package jmine.tec.web.wicket.resource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import jmine.tec.utils.io.IOUtils;

/**
 * {@link ResourceStore} que guarda em memoria
 * 
 * @author takeshi
 */
public class InMemoryResourceStore implements ResourceStore, Serializable {

    private final byte[] data;

    private final boolean compress;

    private final long length;

    /**
     * Equivalente a chamar {@link #InMemoryResourceStore(InputStream, boolean)} com true
     * 
     * @param input {@link InputStream}
     * @throws IOException e
     */
    public InMemoryResourceStore(InputStream input) throws IOException {
        this(input, true);
    }

    /**
     * C'tor
     * 
     * @param input a entrada
     * @param compress se true, vai compactar a entrada usando GZIP
     * @throws IOException e
     */
    public InMemoryResourceStore(InputStream input, boolean compress) throws IOException {
        this.compress = compress;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        OutputStream effective = compress ? new GZIPOutputStream(bout) : bout;
        this.length = IOUtils.copyFullyCloseGetTotal(input, effective);
        this.data = bout.toByteArray();
    }

    /**
     * {@inheritDoc}
     */
    public long length() {
        return length;
    }

    /**
     * {@inheritDoc}
     */
    public InputStream openNew() throws IOException {
        if (compress) {
            return new GZIPInputStream(new ByteArrayInputStream(this.data));
        } else {
            return new ByteArrayInputStream(this.data);
        }
    }

}
